<?php

namespace App\Http\Controllers;

use App\Http\Requests\SellRequests;
use App\Models\BuyRepayment;
use App\Models\Stuns;
use Illuminate\Http\Request;

class BuyRepaymentController extends Controller
{
    use ApiResponse;
    private $buy_repayment,$stuns;

    public function __construct(BuyRepayment $buyRepayment,Stuns $stuns)
    {
        $this->buy_repayment = $buyRepayment;
        $this->stuns = $stuns;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(SellRequests $request)
    {
        $request = $request->all();
        $stone = $this->stuns->find($request['pid']);

        //总还款
        $buy_debt = $this->buy_repayment->where('pid', '=', $request['pid'])->sum('repayment_price');
        //欠款
        $arrears = $stone->price - ($buy_debt + $request['repayment_price']);
        if ($arrears < 0) {
            return $this->failed(TIPS_STONE_FAILED_BUY, 422);
        }
        $data = [
            'repayment_price' =>  $request['repayment_price'],
            'pid' =>  $request['pid'],
            'date_time' =>  $request['date_time'],
        ];


        if($this->buy_repayment->create($data)){
            return $this->message('操作成功!');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if($this->buy_repayment->destroy($id)){
            return $this->message('删除成功！');
        }
    }
}
